<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

</body>
<script>
    // 寻找中间节点
    function findMid(head){
        let slow = head
        let fast = head
        while(slow.next && fast.next.next){
            slow = slow.next
            fast = fast.next.next
        }
        return slow
    }
    // 反转链表
    function reversal(head){
        let prev = null
        let current = head
        while(current){
            const nextTemp = current.next
            current.next = prev
            prev = current
            current = nextTemp
        }
        return prev
    }
    // 判断是否是回文链表
    function isPalindrome(head){
        if(head === null || head.next === null){
            return true
        }
        // 寻找中间节点
        const mid = findMid(head)
        // 下半部分的链表
        const secondHalfHead = mid.next
        mid.next = null
        const reversedSecondHalf = reversal(secondHalfHead)

        // 比较前半部分和反转的后半部分
        let p1 = head
        let p2 = reversedSecondHalf
        let result = true
        while(p1 !== null && p2 !== null){
            if (p1.value !== p2.value){
                return false
                break
            }
            p1 = p1.next
            p2 = p2.next
        }
        return result
    }

    class ListNode {
        constructor(value) {
            this.value = value; // 节点存储的数据
            this.next = null;   // 指向下一个节点的指针
        }
    }
    // 创建链表
    function createLinkedList(arr) {
        if (!arr.length) return null;
        const head = new ListNode(arr[0]);
        let current = head;
        for (let i = 1; i < arr.length; i++) {
            current.next = new ListNode(arr[i]);
            current = current.next;
        }
        return head;
    }
    const list = createLinkedList([1, 2, 2, 2]);
    console.log(isPalindrome(list))
</script>
</html>